package com.springboot.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.demo.entity.*;
import com.springboot.demo.exception.BusinessException;
import com.springboot.demo.mapper.TableMapper;
import com.springboot.demo.service.TableService;
import com.springboot.demo.utils.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.text.ParseException;
import java.util.*;
import java.util.function.BooleanSupplier;

/**
 * @author wubc683
 * @desc
 * @date 2021-11-18 17:08
 */
@Service
public class TableServiceImpl implements TableService {
    @Autowired
    PageUtils pageUtils;
    @Autowired
    TableMapper tableMapper;

    private final String[] DATA_TABLE = {"用户表", "设备表", "场景表", "历史数据表", "历史报警表"};
    private final String[] USER_TABLE = {"用户名", "手机号", "角色名", "电话是否校验", "注册日期-月", "注册日期-周", "注册日期-日", "注册日期-小时",
            "注册日期-分钟"};
    private final String[] DEVICE_TABLE = {"设备名称", "mac地址", "设备群组", "设备状态", "省", "市", "区", "注册日期-月", "注册日期-周",
            "注册日期-日", "注册日期-小时", "注册日期-分钟"};
    private final String[] SCENE_TABLE = {"场景名称", "场景群组", "场景状态", "设备名称", "创建日期-月", "创建日期-周",
            "创建日期-日", "创建日期-小时", "创建日期-分钟"};
    private final String[] HISTORY_DATA_TABLE = {"变量名称", "变量值", "设备名称", "场景名称", "产生日期-月", "产生日期-周",
            "产生日期-日", "产生日期-小时", "产生日期-分钟"};
    private final String[] HISTORY_ALARM_TABLE = {"报警类型", "触发变量", "触发值", "报警内容", "设备名称",
            "场景名称", "产生日期-月", "产生日期-周", "产生日期-日", "产生日期-小时", "产生日期-分钟"};
    private final String[] FILTER_FIELD_MODE = {"等于", "不等于", "小于等于", "大于等于", "小于", "大于", "选择范围", "包含", "不包含",
            "为空", "不为空"};

    @Override
    public PageResult getAllTables(Long uid, String search, Integer type, String sort, Date startDate,
                                   Date endDate, PageRequest pageRequest) {
        // 校验报表类型
        if (type != null && (type < Constant.TableType.INDEX || type > Constant.TableType.PIECHART)) {
            throw new BusinessException(ResponseResult.TABLE_TYPE_ERROR);
        }
        // 校验起始时间和结束时间
        if (startDate != null && endDate != null && startDate.compareTo(endDate) > 0) {
            throw new BusinessException(ResponseResult.START_DATE_LARGER_THAN_END_DATE);
        }
        // 校验排序字段格式
        if (sort != null) {
            String[] split = sort.split("\\s+");
            if (split.length != 2 || (!"desc".equals(split[1]) && !"asc".equals(split[1]))
                    || (!"title".equals(split[0]) && !"type".equals(split[0])
                    && !"ownerName".equals(split[0]) && !"createDate".equals(split[0]))) {
                throw new BusinessException(ResponseResult.SORT_FIELD_FORMAT_ERROR);
            }
        }
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Table> allTables = tableMapper.getAllTables(uid, search, type, sort, startDate, endDate);
        return pageUtils.getPageResult(pageRequest, new PageInfo<>(allTables));
    }

    @Override
    public Table getTable(Long uid, Long tid) {
        // 检查报表id是否属于用户
        Table tableById = tableMapper.getTableById(tid);
        if (tableById == null || !tableById.getOwnerId().equals(uid)) {
            throw new BusinessException(ResponseResult.USER_DO_NOT_HAVE_THIS_TABLE);
        }
        // 查询过滤条件
        List<TableFilter> tableFilter = tableMapper.getTableFilter(tid);
        tableById.setFilters(tableFilter);
        return tableById;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTable(Long uid, Table table) {
        // 检查报表标题是否重复
        Long id = tableMapper.getTableIdByOwnerIdAndTitle(uid, table.getTitle());
        if (id != null) {
            throw new BusinessException(ResponseResult.TABLE_TITLE_DUPLICATE);
        }
        // 校验报表类型
        if (table.getType().compareTo(Constant.TableType.INDEX) < 0
                || table.getType().compareTo(Constant.TableType.PIECHART) > 0) {
            throw new BusinessException(ResponseResult.TABLE_TYPE_ERROR);
        }
        // 校验报表中数据表，维度，对比，值，值类型
        checkTableField(table);
        // 指标卡没有导出功能
        if (table.getDataTableType().equals(Constant.TableType.INDEX) && table.getIsExportAllowed() != null) {
            throw new BusinessException(ResponseResult.TABLE_INDEX_NOT_ALLOW_EXPORT);
        }
        // 校验过滤条件
        checkTableFilter(table);
        // 存入数据库
        table.setOwnerId(uid);
        table.setCreateDate(new Date());
        tableMapper.saveTable(table);
        if (table.getFilters() != null && !table.getFilters().isEmpty()) {
            tableMapper.saveTableFilter(table.getId(), table.getFilters());
            tableMapper.saveTableFilterData(table.getFilters());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTable(Long uid, Table table) {
        // 检查报表是否属于用户
        Table tableById = tableMapper.getTableById(table.getId());
        if (tableById == null || !tableById.getOwnerId().equals(uid)) {
            throw new BusinessException(ResponseResult.USER_DO_NOT_HAVE_THIS_TABLE);
        }
        // 检查报表标题是否重复
        Long tableIdByOwnerIdAndTitle = tableMapper.getTableIdByOwnerIdAndTitle(uid, table.getTitle());
        if (tableIdByOwnerIdAndTitle != null && !tableIdByOwnerIdAndTitle.equals(table.getId())) {
            throw new BusinessException(ResponseResult.TABLE_TITLE_DUPLICATE);
        }
        // 校验报表类型
        if (table.getType().compareTo(Constant.TableType.INDEX) < 0
                || table.getType().compareTo(Constant.TableType.PIECHART) > 0) {
            throw new BusinessException(ResponseResult.TABLE_TYPE_ERROR);
        }
        // 校验报表中数据表，维度，对比，值，值类型
        checkTableField(table);
        // 指标卡没有导出功能
        if (table.getDataTableType().equals(Constant.TableType.INDEX) && table.getIsExportAllowed() != null) {
            throw new BusinessException(ResponseResult.TABLE_INDEX_NOT_ALLOW_EXPORT);
        }
        // 校验过滤条件
        checkTableFilter(table);
        // 存入数据库
        tableMapper.updateTable(table);
        // 先删除原有过滤条件，再增加
        tableMapper.deleteTableFilter(table.getId());
        if (table.getFilters() != null && !table.getFilters().isEmpty()) {
            tableMapper.saveTableFilter(table.getId(), table.getFilters());
            tableMapper.saveTableFilterData(table.getFilters());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTable(Long uid, List<Long> tableIds) {
        // 检查报表是否属于用户
        List<Long> tableIdByUid = tableMapper.getTableIdByUid(uid);
        Set<Long> set = new HashSet<>(tableIdByUid);
        for (Long id : tableIds) {
            if (!set.contains(id)) {
                throw new BusinessException(ResponseResult.USER_DO_NOT_HAVE_THIS_TABLE);
            }
        }
        // 删除报表基本信息
        tableMapper.deleteTableInBatches(tableIds);
        // 删除报表过滤条件
        tableMapper.deleteTableFilterInBatches(tableIds);
        // 删除仪表盘中报表
        tableMapper.deletePanelTableInBatches(tableIds);
    }

    @Override
    public PageResult getTableData(Long uid, Long tid, String sort, PageRequest request) {
        // 检查报表是否属于用户
        Table tableById = tableMapper.getTableById(tid);
        if (tableById == null || !tableById.getOwnerId().equals(uid)) {
            throw new BusinessException(ResponseResult.USER_DO_NOT_HAVE_THIS_TABLE);
        }
        // 查询过滤条件
        List<TableFilter> tableFilter = tableMapper.getTableFilter(tid);
        tableById.setFilters(tableFilter);
        return getUnSavedTableData(uid, tableById, sort, request);
    }

    @Override
    public PageResult getUnSavedTableData(Long uid, Table table, String sort, PageRequest request) {
        // 校验报表数据表类型
        if (table.getType().compareTo(Constant.TableType.INDEX) < 0
                || table.getType().compareTo(Constant.TableType.PIECHART) > 0) {
            throw new BusinessException(ResponseResult.TABLE_TYPE_ERROR);
        }
        // 校验报表中数据表，维度，对比，值，值类型
        checkTableField(table);
        // 校验过滤条件
        checkTableFilter(table);
        // 获取报表过滤值,单独取出来处理，防止sql注入
        List<TableFilterValue> tableFilterValue = getTableFilterValue(table.getDataTableType(), table.getFilters());
        if (table.getType().equals(Constant.TableType.INDEX)) {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            Double indexTableData = tableMapper.getIndexTableData(table, tableFilterValue);
            Map<String, Object> m = new HashMap<>();
            m.put("content", indexTableData);
            m.put("title", table.getTitle());
            m.put("type", table.getType());
            return pageUtils.getPageResult(request, new PageInfo<>(Collections.singletonList(m)));
        } else if (table.getType().equals(Constant.TableType.PIECHART)) {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            List<Map<String, Object>> tablePieData = tableMapper.getTablePieData(table, tableFilterValue);
            // 检查报表维度数量是否超限
            if (tablePieData.size() > Constant.TABLE_COMPARE_MAX_COUNT) {
                throw new BusinessException(ResponseResult.TABLE_PIE_DIMENSION_EXCEED_LIMIT);
            }
            if (tablePieData.size() == 0) {
                return pageUtils.getPageResult(request, new PageInfo<>(tablePieData));
            }
            Map<String, Object> m = new HashMap<>();
            m.put("title", table.getTitle());
            m.put("type", table.getType());
            tablePieData.add(m);
            return pageUtils.getPageResult(request, new PageInfo<>(tablePieData));
        } else {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            List<String> tableCompareField = tableMapper.getTableTableCompareFieldSql(table, tableFilterValue);
            // 检查报表对比值数量是否超限
            if (tableCompareField.size() > Constant.TABLE_COMPARE_MAX_COUNT) {
                throw new BusinessException(ResponseResult.TABLE_COMPARE_COUNT_EXCEED_LIMIT);
            }
            if (tableCompareField.size() == 0) {
                return pageUtils.getPageResult(request, new PageInfo<>(tableCompareField));
            }
            // 校验sort格式
            checkSortFormat(sort, tableCompareField);

            List<Map<String, Object>> tableTableData = tableMapper.getTableTableData(table, tableCompareField,
                    tableFilterValue, sort);
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> m = new HashMap<>();
            for (int i = 0; i < tableCompareField.size(); i++) {
                m.put(String.valueOf(i), tableCompareField.get(i));
            }
            m.put("dimension", getTableFieldName(table.getDataTableType(), table.getDimension()));
            map.put("heads", m);
            Map<String, Object> title = new HashMap<>();
            title.put("title", table.getTitle());
            title.put("type", table.getType());
            map.putAll(title);
            tableTableData.add(map);
            return pageUtils.getPageResult(request, new PageInfo<>(tableTableData));
        }
    }

    /**
     * 校验排序字段格式
     *
     * @param sort
     * @param tableCompareField
     * @return: void
     */
    private void checkSortFormat(String sort, List<String> tableCompareField) {
        if (!StringUtils.isEmpty(sort)) {
            String[] s = sort.split("\\s+");
            if (s.length == 2 && ("desc".equals(s[1]) || "asc".equals(s[1]))) {
                int column = s[0].indexOf("column");
                if (column == -1) {
                    throw new BusinessException(ResponseResult.SORT_FIELD_FORMAT_ERROR);
                }
                String tail = s[0].replace("column", "");
                int num;
                try {
                    num = Integer.parseInt(tail);
                } catch (NumberFormatException e) {
                    throw new BusinessException(ResponseResult.SORT_FIELD_FORMAT_ERROR);
                }
                if (num < 0 || num >= tableCompareField.size()) {
                    throw new BusinessException(ResponseResult.SORT_FIELD_FORMAT_ERROR);
                }
            } else {
                throw new BusinessException(ResponseResult.SORT_FIELD_FORMAT_ERROR);
            }
        }
    }

    /**
     * 校验报表过滤条件
     *
     * @param table
     * @return: void
     */
    private void checkTableFilter(Table table) {
        List<TableFilter> filters = table.getFilters();
        if (filters == null || filters.size() == 0) {
            return;
        }
        // 获取不同数据表字段序号最小为1，最大为表长度
        int maxFieldNo = getMaxFieldNoFromDiffDataTable(table.getDataTableType());
        Set<Integer> fields = new HashSet<>();
        for (TableFilter filter : filters) {
            // 校验过滤字段是否有效
            if (filter.getFilterField() < 1 || filter.getFilterField() > maxFieldNo) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_VALUE_TYPE_ERROR);
            }
            // 校验过滤字段是否重复
            if (fields.contains(filter.getFilterField())) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_DUPLICATE);
            } else {
                fields.add(filter.getFilterField());
            }
            // 校验过滤模式,最小为1
            int maxFilterModeNo = FILTER_FIELD_MODE.length;
            if (filter.getFilterMode() < 1 || filter.getFilterMode() > maxFilterModeNo) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_ERROR);
            }
            // 校验过滤字段长度是否超过限制
            for (String s : filter.getFilterData()) {
                if (s.length() > Constant.MAX_FILTER_DATA_LENGTH) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_DATA_LENGTH_EXCEED_LIMIT);
                }
            }
            // 校验过滤字段与过滤模式是否匹配
            // 常规字段,包含模式：1:等于,2:不等于,8:包含,9:不包含,10:为空,11:不为空
            boolean b1 = (table.getDataTableType().equals(Constant.DataTable.USER)
                    && (filter.getFilterField().equals(Constant.UserTable.USERNAME)
                    || filter.getFilterField().equals(Constant.UserTable.PHONE)
                    || filter.getFilterField().equals(Constant.UserTable.ROLE)));
            boolean b2 = (table.getDataTableType().equals(Constant.DataTable.DEVICE)
                    && (filter.getFilterField().equals(Constant.DeviceTable.DEVICE_NAME)
                    || filter.getFilterField().equals(Constant.DeviceTable.DEVICE_CLUSTER)
                    || filter.getFilterField().equals(Constant.DeviceTable.MAC_ADDR)
                    || filter.getFilterField().equals(Constant.DeviceTable.PROVINCE)
                    || filter.getFilterField().equals(Constant.DeviceTable.CITY)
                    || filter.getFilterField().equals(Constant.DeviceTable.REGION)));
            boolean b3 = (table.getDataTableType().equals(Constant.DataTable.SCENE)
                    && (filter.getFilterField().equals(Constant.SceneTable.SCENE_NAME)
                    || filter.getFilterField().equals(Constant.SceneTable.SCENE_GROUP)
                    || filter.getFilterField().equals(Constant.SceneTable.DEVICE_NAME)));
            boolean b4 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_DATA)
                    && (filter.getFilterField().equals(Constant.HistoryDataTable.DEVICE_NAME)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.SCENE_NAME)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.VAR_NAME)));
            boolean b5 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_ALARM)
                    && (filter.getFilterField().equals(Constant.HistoryAlarmTable.ALARM_TEXT)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.DEVICE_NAME)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.SCENE_NAME)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_VAR)));

            if (b1 || b2 || b3 || b4 || b5) {
                if (!filter.getFilterMode().equals(Constant.FilterMode.EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.CONTAIN)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_CONTAIN)
                        && !filter.getFilterMode().equals(Constant.FilterMode.EMPTY)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
                }
            }
            // 固定选项字段，包含模式：1:等于,2:不等于,10:为空,11:不为空
            boolean b6 = (table.getDataTableType().equals(Constant.DataTable.USER)
                    && (filter.getFilterField().equals(Constant.UserTable.IS_PHONE_CHECKED)));
            boolean b7 = (table.getDataTableType().equals(Constant.DataTable.DEVICE)
                    && (filter.getFilterField().equals(Constant.DeviceTable.DEVICE_STATUS)));
            boolean b8 = (table.getDataTableType().equals(Constant.DataTable.SCENE)
                    && (filter.getFilterField().equals(Constant.SceneTable.SCENE_STATUS)));
            boolean b9 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_ALARM)
                    && (filter.getFilterField().equals(Constant.HistoryAlarmTable.ALARM_TYPE)));
            if (b6 || b7 || b8 || b9) {
                if (!filter.getFilterMode().equals(Constant.FilterMode.EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.EMPTY)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
                }
            }
            // 值类型字段，包含模式：1:等于,2:不等于,3:小于等于,4:大于等于,5:小于,6:大于,7:选择范围,10:为空,11:不为空
            boolean b10 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_DATA)
                    && (filter.getFilterField().equals(Constant.HistoryDataTable.VALUE)));
            boolean b11 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_ALARM)
                    && (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_VALUE)));
            if (b10 || b11) {
                if (!filter.getFilterMode().equals(Constant.FilterMode.EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN_OR_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN_OR_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN)
                        && !filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN)
                        && !filter.getFilterMode().equals(Constant.FilterMode.RANGE)
                        && !filter.getFilterMode().equals(Constant.FilterMode.EMPTY)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
                }
            }
            // 时间类型字段，包含模式：1:等于,2:不等于,3:小于等于,4:大于等于,7:选择范围,10:为空,11:不为空
            boolean b12 = table.getDataTableType().equals(Constant.DataTable.USER)
                    && (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_MONTH)
                    || filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_WEEK)
                    || filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_DAY)
                    || filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_HOUR)
                    || filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_MINUTE));
            boolean b13 = (table.getDataTableType().equals(Constant.DataTable.DEVICE)
                    && (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_MONTH)
                    || filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_WEEK)
                    || filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_DAY)
                    || filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_HOUR)
                    || filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_MINUTE)));
            boolean b14 = (table.getDataTableType().equals(Constant.DataTable.SCENE)
                    && (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_MONTH)
                    || filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_WEEK)
                    || filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_DAY)
                    || filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_HOUR)
                    || filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_MINUTE)));
            boolean b15 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_DATA)
                    && (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_MONTH)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_WEEK)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_DAY)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_HOUR)
                    || filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_MINUTE)));
            boolean b16 = (table.getDataTableType().equals(Constant.DataTable.HISTORY_ALARM)
                    && (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_MONTH)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_WEEK)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_DAY)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_HOUR)
                    || filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_MINUTE)));
            if (b12 || b13 || b14 || b15 || b16) {
                if (!filter.getFilterMode().equals(Constant.FilterMode.EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN_OR_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN_OR_EQUAL)
                        && !filter.getFilterMode().equals(Constant.FilterMode.RANGE)
                        && !filter.getFilterMode().equals(Constant.FilterMode.EMPTY)
                        && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
                }
            }
            // 校验过滤值类型是否有效
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.HALF_AN_HOUR)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.HOUR)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.ONE_DAY)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.ONE_MONTH)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.ONE_YEAR)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.SEVEN_DAY)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.SIX_HOUR)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.SIX_MONTH)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_SINGLE)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.THREE_HOUR)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.THREE_MONTH)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_DOUBLE)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_FIXED)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_SINGLE)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.TWO_DAY)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.VALUE_DOUBLE)
                    && !filter.getFilterDataType().equals(Constant.TableFilterDataType.VALUE_SINGEL)
            ) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_DATA_TYPE_ERROR);
            }
            // 过滤值类型为字符串多值数量大于1,其余均等于1
            if ((filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)
                    && filter.getFilterData().size() < 1)
                    || (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)
                    && filter.getFilterData().size() != 1)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_DATA_NUM_ERROR);
            }
            // 校验过滤值格式
        }
        // 返回值不需要，只是为了校验过滤值的格式
        getTableFilterValue(table.getDataTableType(), table.getFilters());
    }

    /**
     * 获取报表过滤值
     *
     * @param dataTableType
     * @param filters
     * @return: java.util.List<java.lang.String>
     */
    private List<TableFilterValue> getTableFilterValue(Integer dataTableType, List<TableFilter> filters) {
        List<TableFilterValue> list = new ArrayList<>();
        for (int i = 0; i < filters.size(); i++) {
            TableFilter filter = filters.get(i);
            List<String> filterValue = new ArrayList<>();
            // 用户表
            if (dataTableType.equals(Constant.DataTable.USER)) {
                if (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_MONTH)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_WEEK)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_DAY)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_HOUR)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.CREATE_DATE_MINUTE)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.IS_PHONE_CHECKED)) {
                    filterValue = getFixedFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.ROLE)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.PHONE)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.UserTable.USERNAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_TYPE_ERROR);
                }
            } else if (dataTableType.equals(Constant.DataTable.DEVICE)) { // 设备表
                if (filter.getFilterField().equals(Constant.DeviceTable.REGION)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CITY)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.PROVINCE)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.MAC_ADDR)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_MONTH)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_WEEK)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_DAY)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_HOUR)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.CREATE_DATE_MINUTE)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.DEVICE_STATUS)) {
                    filterValue = getFixedFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.DEVICE_CLUSTER)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.DeviceTable.DEVICE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_TYPE_ERROR);
                }
            } else if (dataTableType.equals(Constant.DataTable.SCENE)) { // 场景表
                if (filter.getFilterField().equals(Constant.SceneTable.SCENE_GROUP)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.DEVICE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.SCENE_STATUS)) {
                    filterValue = getFixedFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_MONTH)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_WEEK)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_DAY)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_HOUR)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.CREATE_DATE_MINUTE)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.SceneTable.SCENE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_TYPE_ERROR);
                }
            } else if (dataTableType.equals(Constant.DataTable.HISTORY_DATA)) { // 历史数据表
                if (filter.getFilterField().equals(Constant.HistoryDataTable.DEVICE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.SCENE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.VAR_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.VALUE)) {
                    filterValue = getValueFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_MONTH)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_WEEK)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_DAY)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_HOUR)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryDataTable.PRODUCT_TIME_MINUTE)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_TYPE_ERROR);
                }
            } else if (dataTableType.equals(Constant.DataTable.HISTORY_ALARM)) { // 历史报警表
                if (filter.getFilterField().equals(Constant.HistoryAlarmTable.ALARM_TEXT)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.DEVICE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.SCENE_NAME)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_VAR)) {
                    filterValue = getFlexiableFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.ALARM_TYPE)) {
                    filterValue = getFixedFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_VALUE)) {
                    filterValue = getValueFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_MONTH)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_WEEK)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_DAY)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_HOUR)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else if (filter.getFilterField().equals(Constant.HistoryAlarmTable.TRIGGER_TIME_MINUTE)) {
                    filterValue = getTimeFieldFilterValue(filter);
                } else {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_FIELD_TYPE_ERROR);
                }
            } else {
                throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_TYPE_ERROR);
            }
            TableFilterValue tableFilterValue = new TableFilterValue();
            tableFilterValue.setFilterValue(filterValue);
            list.add(tableFilterValue);
//            setTableFilterValueList(list, i, filterValue);
        }
        return list;
    }


    /**
     * 获取报表可变字段过滤值
     *
     * @param filter
     * @return: java.util.List<java.lang.String>
     */
    private List<String> getFlexiableFieldFilterValue(TableFilter filter) {
//        String[] split = filter.getFilterData().split("\\s+");
//        List<String> list = Arrays.asList(split);
        if (filter.getFilterMode().equals(Constant.FilterMode.EQUAL)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.CONTAIN)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_SINGLE)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_CONTAIN)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_SINGLE)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.EMPTY)) {
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
        } else {
            throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
        }
        return filter.getFilterData();
    }

    /**
     * 获取报表固定字段过滤值
     *
     * @param filter
     * @return: java.util.List<java.lang.String>
     */
    private List<String> getFixedFieldFilterValue(TableFilter filter) {
//        List<String> list = new ArrayList<>();
//        list.add(filter.getFilterData());
        if (filter.getFilterMode().equals(Constant.FilterMode.EQUAL)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.STRING_MANY)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.EMPTY)) {
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
        } else {
            throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
        }
        return filter.getFilterData();
    }

    /**
     * 获取报表校验值过滤值
     *
     * @param filter
     * @return: java.util.List<java.lang.String>
     */
    private List<String> getValueFieldFilterValue(TableFilter filter) {
        List<String> list = new ArrayList<>();
        // 过滤数据需要转换为list
        String data = filter.getFilterData().get(0);
        if (filter.getFilterMode().equals(Constant.FilterMode.EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN_OR_EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN_OR_EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN)
                || filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.VALUE_SINGEL)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
            try {
                Float aFloat = Float.valueOf(data);
                list.add(String.valueOf(aFloat));
            } catch (NumberFormatException e) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_VALUE_ILLEGAL);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.RANGE)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.VALUE_DOUBLE)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
            Object min = null, max = null;
            try {
                JSONObject jsonObject = null;
                JSONValidator jsonValidator = JSONValidator.from(data);
                if (!jsonValidator.validate()) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_VALUE_JSON_PARSE_ERROR);
                }
                jsonObject = JSONObject.parseObject(data);
                if (jsonObject == null || (!jsonObject.containsKey("min") && !jsonObject.containsKey("max"))) {
                    throw new BusinessException(ResponseResult.TABLE_FILTER_DATA_FORMAT_ERROR);
                }
                if (jsonObject.containsKey("min")) {
                    min = jsonObject.get("min");
                    if (min != null) {
                        Float aFloat = Float.valueOf(min.toString());
                        list.add(String.valueOf(aFloat));
                    } else {
                        list.add("");
                    }
                }
                if (jsonObject.containsKey("max")) {
                    max = jsonObject.get("max");
                    if (max != null) {
                        Float aFloat = Float.valueOf(max.toString());
                        list.add(String.valueOf(aFloat));
                    } else {
                        list.add("");
                    }
                }
            } catch (NumberFormatException e) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_VALUE_ILLEGAL);
            }
            if (min != null && max != null && Float.parseFloat(min.toString()) > Float.parseFloat(max.toString())) {
                throw new BusinessException(ResponseResult.MIN_VALUE_LARGER_THAN_MAX_VALUE);
            }
        } else if (!filter.getFilterMode().equals(Constant.FilterMode.EMPTY)
                && !filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
            throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
        }
        return list;
    }

    /**
     * 获取报表时间字段过滤值
     *
     * @param filter
     * @return: java.util.List<java.lang.String>
     */
    private List<String> getTimeFieldFilterValue(TableFilter filter) {
        List<String> list = new ArrayList<>();
        // 过滤数据需要转换为list
        String data = filter.getFilterData().get(0);
        if (filter.getFilterMode().equals(Constant.FilterMode.EQUAL)) {
            if (filter.getFilterDataType().compareTo(Constant.TableFilterDataType.TIME_FIXED) < 0
                    || filter.getFilterDataType().compareTo(Constant.TableFilterDataType.ONE_YEAR) > 0) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
            if (filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_FIXED)) {
                try {
                    if (!"".equals(data)) {
                        Date parse = DateUtils.parse(data);
                        list.add(String.valueOf(parse));
                    } else {
                        list.add("");
                    }
                } catch (ParseException e) {
                    throw new BusinessException(ResponseResult.TIME_PARSE_ERROR);
                }
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.LESS_THAN_OR_EQUAL)
                || filter.getFilterMode().equals(Constant.FilterMode.MORE_THAN_OR_EQUAL)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_SINGLE)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
            try {
                if (!"".equals(data)) {
                    Date parse = DateUtils.parse(data);
                    list.add(String.valueOf(parse));
                } else {
                    list.add("");
                }
            } catch (ParseException e) {
                throw new BusinessException(ResponseResult.TIME_PARSE_ERROR);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.RANGE)) {
            if (!filter.getFilterDataType().equals(Constant.TableFilterDataType.TIME_DOUBLE)) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_VALUE_TYPE);
            }
            JSONObject jsonObject = null;
            JSONValidator jsonValidator = JSONValidator.from(data);
            if (!jsonValidator.validate()) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_VALUE_JSON_PARSE_ERROR);
            }
            jsonObject = JSONObject.parseObject(data);
            Date startDate = null, endDate = null;

            if (jsonObject == null || (!jsonObject.containsKey("startDate") && !jsonObject.containsKey("endDate"))) {
                throw new BusinessException(ResponseResult.TABLE_FILTER_DATA_FORMAT_ERROR);
            }
            if (jsonObject.containsKey("startDate")) {
                try {
                    Object startDate1 = jsonObject.get("startDate");
                    if (startDate1 != null && !"".equals(startDate1)) {
                        startDate = DateUtils.parse(startDate1.toString());
                        list.add(String.valueOf(startDate));
                    } else {
                        list.add("");
                    }
                } catch (ParseException e) {
                    throw new BusinessException(ResponseResult.TIME_PARSE_ERROR);
                }
            }
            if (jsonObject.containsKey("endDate")) {
                try {
                    Object endDate1 = jsonObject.get("endDate");
                    if (endDate1 != null && !"".equals(endDate1)) {
                        endDate = DateUtils.parse(endDate1.toString());
                        list.add(String.valueOf(endDate));
                    } else {
                        list.add("");
                    }
                } catch (ParseException e) {
                    throw new BusinessException(ResponseResult.TIME_PARSE_ERROR);
                }
            }
            // 起始时间和结束时间必须有2个值
            if (startDate != null && endDate != null && startDate.compareTo(endDate) > 0) {
                throw new BusinessException(ResponseResult.START_DATE_LARGER_THAN_END_DATE);
            }
        } else if (filter.getFilterMode().equals(Constant.FilterMode.EMPTY)) {
        } else if (filter.getFilterMode().equals(Constant.FilterMode.NOT_EMPTY)) {
        } else {
            throw new BusinessException(ResponseResult.TABLE_FILTER_MODE_NOT_MATCH_FIELD);
        }
        return list;
    }

    /**
     * 校验报表中数据表，维度，对比，值，值类型
     *
     * @param table
     * @return: void
     */
    private void checkTableField(Table table) {
        // 校验数据表类型,数据表序号最小为1，最大为数据表数组长度
        int maxDataTableNo = DATA_TABLE.length;
        if (table.getDataTableType() < 1 || table.getDataTableType() > maxDataTableNo) {
            throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_TYPE_ERROR);
        }
        // 获取不同数据表字段序号最小为1，最大为表长度
        int maxFieldNo = getMaxFieldNoFromDiffDataTable(table.getDataTableType());
        // 校验维度字段,指标卡此字段忽略
        if (!table.getType().equals(Constant.TableType.INDEX)
                && (table.getDimension().compareTo(1) < 0 || table.getDimension() > maxFieldNo)) {
            throw new BusinessException(ResponseResult.TABLE_DIMENSION_TYPE_ERROR);
        }
        // 校验对比字段,指标卡和饼图忽略此字段
        if (!table.getType().equals(Constant.TableType.INDEX) && !table.getType().equals(Constant.TableType.PIECHART)
                && (table.getCompare().compareTo(1) < 0 || table.getCompare() > maxFieldNo)) {
            throw new BusinessException(ResponseResult.TABLE_COMPARE_TYPE_ERROR);
        }
        // 校验值字段
        if (table.getValue().compareTo(1) < 0 || table.getValue() > maxFieldNo) {
            throw new BusinessException(ResponseResult.TABLE_VALUE_TYPE_ERROR);
        }
        // 校验值类型,除历史变量表的变量值：2，和历史报警表的触发值：4使用值相关统计类型，其余均使用计数和去重计数方式
        boolean b = (table.getDataTableType().equals(Constant.DataTable.HISTORY_DATA)
                && table.getValue().equals(Constant.HistoryDataTable.VALUE))
                || (table.getDataTableType().equals(Constant.DataTable.HISTORY_ALARM)
                && table.getValue().equals(Constant.HistoryAlarmTable.TRIGGER_VALUE));
        if (b) {
            if (table.getValueType() < Constant.TableValueType.AVG || table.getValueType() > Constant.TableValueType.LAST) {
                throw new BusinessException(ResponseResult.TABLE_VALUE_COUNT_TYPE_ERROR);
            }
        } else if (!table.getValueType().equals(Constant.TableValueType.COUNT)
                && !table.getValueType().equals(Constant.TableValueType.COUNT_UNIQUE)) {
            throw new BusinessException(ResponseResult.TABLE_VALUE_COUNT_TYPE_ERROR);
        }
    }

    /**
     * 从不同数据表获取字段最大序号
     *
     * @param dataTableType
     * @return: int
     */
    private int getMaxFieldNoFromDiffDataTable(Integer dataTableType) {
        int maxFieldNo;
        if (dataTableType.equals(Constant.DataTable.USER)) {
            maxFieldNo = USER_TABLE.length;
        } else if (dataTableType.equals(Constant.DataTable.DEVICE)) {
            maxFieldNo = DEVICE_TABLE.length;
        } else if (dataTableType.equals(Constant.DataTable.SCENE)) {
            maxFieldNo = SCENE_TABLE.length;
        } else if (dataTableType.equals(Constant.DataTable.HISTORY_DATA)) {
            maxFieldNo = HISTORY_DATA_TABLE.length;
        } else if (dataTableType.equals(Constant.DataTable.HISTORY_ALARM)) {
            maxFieldNo = HISTORY_ALARM_TABLE.length;
        } else {
            throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_TYPE_ERROR);
        }
        return maxFieldNo;
    }

    @Override
    public List<TableType> getTableTypes() {
        List<TableType> tableTypes = new ArrayList<>();
        tableTypes.add(new TableType(Constant.TableType.INDEX, "指标卡", true, true, false, false, true, true, false));
        tableTypes.add(new TableType(Constant.TableType.TABLE, "列表", true, true, true, true, true, true, true));
        tableTypes.add(new TableType(Constant.TableType.LINEGRAPH, "折线图", true, true, true, true, true, true, true));
        tableTypes.add(new TableType(Constant.TableType.HISTOGRAM, "柱状图", true, true, true, true, true, true, true));
        tableTypes.add(new TableType(Constant.TableType.STACKEDCHART, "堆叠柱状图", true, true, true, true, true, true, true));
        tableTypes.add(new TableType(Constant.TableType.BARGRAPH, "条形图", true, true, true, true, true, true, true));
        tableTypes.add(new TableType(Constant.TableType.PIECHART, "饼图", true, true, true, false, true, true, true));
        return tableTypes;
    }

    @Override
    public List<TableDataTable> getTableDataTables() {
        List<TableDataTable> tableDataTables = new ArrayList<>();
        TableDataTable dataTable = new TableDataTable();
        dataTable.setDataTableNo(Constant.DataTable.USER);
        dataTable.setDataTableName(DATA_TABLE[0]);
        List<TableDataTableField> tableDataTableFields = new ArrayList<>();
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.USERNAME, USER_TABLE[0]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.PHONE, USER_TABLE[1]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.ROLE, USER_TABLE[2]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.IS_PHONE_CHECKED, USER_TABLE[3]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.CREATE_DATE_MONTH, USER_TABLE[4]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.CREATE_DATE_WEEK, USER_TABLE[5]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.CREATE_DATE_DAY, USER_TABLE[6]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.CREATE_DATE_HOUR, USER_TABLE[7]));
        tableDataTableFields.add(new TableDataTableField(Constant.UserTable.CREATE_DATE_MINUTE, USER_TABLE[8]));
        dataTable.setTableDataTableFields(tableDataTableFields);
        tableDataTables.add(dataTable);

        dataTable = new TableDataTable();
        dataTable.setDataTableNo(Constant.DataTable.DEVICE);
        dataTable.setDataTableName(DATA_TABLE[1]);
        tableDataTableFields = new ArrayList<>();
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.DEVICE_NAME, DEVICE_TABLE[0]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.MAC_ADDR, DEVICE_TABLE[1]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.DEVICE_CLUSTER, DEVICE_TABLE[2]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.DEVICE_STATUS, DEVICE_TABLE[3]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.PROVINCE, DEVICE_TABLE[4]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CITY, DEVICE_TABLE[5]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.REGION, DEVICE_TABLE[6]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CREATE_DATE_MONTH, DEVICE_TABLE[7]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CREATE_DATE_WEEK, DEVICE_TABLE[8]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CREATE_DATE_DAY, DEVICE_TABLE[9]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CREATE_DATE_HOUR, DEVICE_TABLE[10]));
        tableDataTableFields.add(new TableDataTableField(Constant.DeviceTable.CREATE_DATE_MINUTE, DEVICE_TABLE[11]));
        dataTable.setTableDataTableFields(tableDataTableFields);
        tableDataTables.add(dataTable);

        dataTable = new TableDataTable();
        dataTable.setDataTableNo(Constant.DataTable.SCENE);
        dataTable.setDataTableName(DATA_TABLE[2]);
        tableDataTableFields = new ArrayList<>();
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.SCENE_NAME, SCENE_TABLE[0]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.SCENE_GROUP, SCENE_TABLE[1]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.SCENE_STATUS, SCENE_TABLE[2]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.DEVICE_NAME, SCENE_TABLE[3]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.CREATE_DATE_MONTH, SCENE_TABLE[4]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.CREATE_DATE_WEEK, SCENE_TABLE[5]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.CREATE_DATE_DAY, SCENE_TABLE[6]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.CREATE_DATE_HOUR, SCENE_TABLE[7]));
        tableDataTableFields.add(new TableDataTableField(Constant.SceneTable.CREATE_DATE_MINUTE, SCENE_TABLE[8]));
        dataTable.setTableDataTableFields(tableDataTableFields);
        tableDataTables.add(dataTable);

        dataTable = new TableDataTable();
        dataTable.setDataTableNo(Constant.DataTable.HISTORY_DATA);
        dataTable.setDataTableName(DATA_TABLE[3]);
        tableDataTableFields = new ArrayList<>();
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.VAR_NAME, HISTORY_DATA_TABLE[0]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.VALUE, HISTORY_DATA_TABLE[1]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.DEVICE_NAME, HISTORY_DATA_TABLE[2]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.SCENE_NAME, HISTORY_DATA_TABLE[3]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.PRODUCT_TIME_MONTH,
                HISTORY_DATA_TABLE[4]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.PRODUCT_TIME_WEEK,
                HISTORY_DATA_TABLE[5]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.PRODUCT_TIME_DAY,
                HISTORY_DATA_TABLE[6]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.PRODUCT_TIME_HOUR,
                HISTORY_DATA_TABLE[7]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryDataTable.PRODUCT_TIME_MINUTE,
                HISTORY_DATA_TABLE[8]));
        dataTable.setTableDataTableFields(tableDataTableFields);
        tableDataTables.add(dataTable);

        dataTable = new TableDataTable();
        dataTable.setDataTableNo(Constant.DataTable.HISTORY_ALARM);
        dataTable.setDataTableName(DATA_TABLE[4]);
        tableDataTableFields = new ArrayList<>();
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.ALARM_TYPE, HISTORY_ALARM_TABLE[0]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_VAR, HISTORY_ALARM_TABLE[1]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_VALUE, HISTORY_ALARM_TABLE[2]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.ALARM_TEXT, HISTORY_ALARM_TABLE[3]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.DEVICE_NAME, HISTORY_ALARM_TABLE[4]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.SCENE_NAME, HISTORY_ALARM_TABLE[5]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_TIME_MONTH,
                HISTORY_ALARM_TABLE[6]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_TIME_WEEK,
                HISTORY_ALARM_TABLE[7]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_TIME_DAY,
                HISTORY_ALARM_TABLE[8]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_TIME_HOUR,
                HISTORY_ALARM_TABLE[9]));
        tableDataTableFields.add(new TableDataTableField(Constant.HistoryAlarmTable.TRIGGER_TIME_MINUTE,
                HISTORY_ALARM_TABLE[10]));
        dataTable.setTableDataTableFields(tableDataTableFields);
        tableDataTables.add(dataTable);

        return tableDataTables;
    }

    @Override
    public List<String> getTableFieldData(Long uid, Integer dataTableNum, Integer fieldNum, String search) {
        if (dataTableNum < 1 || dataTableNum > 5) {
            throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_NOT_EXISTED);
        }
        boolean b1 = dataTableNum == 1 && (fieldNum < 1 || fieldNum > 3);
        boolean b2 =
                dataTableNum == 2 && (fieldNum != 1 && fieldNum != 3 && fieldNum != 5 && fieldNum != 6
                        && fieldNum != 7);
        boolean b3 = dataTableNum == 3 && (fieldNum != 1 && fieldNum != 2 && fieldNum != 4);
        boolean b4 = dataTableNum == 4 && (fieldNum != 1 && fieldNum != 3 && fieldNum != 4);
        boolean b5 = dataTableNum == 5 && (fieldNum != 2 && fieldNum != 4 && fieldNum != 5 && fieldNum != 6);
        if (b1 || b2 || b3 || b4 || b5) {
            throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_FIELD_NOT_EXISTED);
        }
        List<String> result = null;
        if (dataTableNum == 1) {
            if (fieldNum == 1) {
                result = tableMapper.getTableFilterFieldUsername(uid, search);
            } else if (fieldNum == 2) {
                result = tableMapper.getTableFilterFieldPhone(uid, search);
            } else {
                result = tableMapper.getTableFilterFieldRole(uid, search);
            }
        } else if (dataTableNum == 2) {
            if (fieldNum == 1) {
                result = tableMapper.getTableFilterFieldDeviceName(uid, search);
            } else if (fieldNum == 3) {
                result = tableMapper.getTableFilterFieldDeviceCluster(uid, search);
            } else if (fieldNum == 5) {
                result = tableMapper.getTableFilterFieldProvince(uid, search);
            } else if (fieldNum == 6) {
                result = tableMapper.getTableFilterFieldCity(uid, search);
            } else {
                result = tableMapper.getTableFilterFieldRegion(uid, search);
            }
        } else if (dataTableNum == 3) {
            if (fieldNum == 1) {
                result = tableMapper.getTableFilterFieldSceneName(uid, search);
            } else if (fieldNum == 2) {
                result = tableMapper.getTableFilterFieldSceneGroupName(uid, search);
            } else {
                result = tableMapper.getTableFilterFieldDeviceName(uid, search);
            }
        } else if (dataTableNum == 4) {
            if (fieldNum == 1) {
                result = tableMapper.getTableFilterFieldVariableName(uid, search);
            } else if (fieldNum == 3) {
                result = tableMapper.getTableFilterFieldDeviceName(uid, search);
            } else {
                result = tableMapper.getTableFilterFieldSceneName(uid, search);
            }
        } else {
            if (fieldNum == 2) {
                result = tableMapper.getTableFilterFieldVariableName(uid, search);
            } else if (fieldNum == 4) {
                result = tableMapper.getTableFilterFieldAlarmContent(uid, search);
            } else if (fieldNum == 5) {
                result = tableMapper.getTableFilterFieldDeviceName(uid, search);
            } else {
                result = tableMapper.getTableFilterFieldSceneName(uid, search);
            }
        }
        return result;
    }

    /**
     * 获取字段名称
     *
     * @param dataTableType
     * @param field
     * @return: java.lang.String
     */
    public String getTableFieldName(Integer dataTableType, Integer field) {
        String res = null;
        if (dataTableType.equals(Constant.DataTable.USER)) {
            if (field >= 1 && field <= USER_TABLE.length) {
                return USER_TABLE[field - 1];
            }
        } else if (dataTableType.equals(Constant.DataTable.DEVICE)) {
            if (field >= 1 && field <= DEVICE_TABLE.length) {
                return DEVICE_TABLE[field - 1];
            }
        } else if (dataTableType.equals(Constant.DataTable.SCENE)) {
            if (field >= 1 && field <= SCENE_TABLE.length) {
                return SCENE_TABLE[field - 1];
            }
        } else if (dataTableType.equals(Constant.DataTable.HISTORY_DATA)) {
            if (field >= 1 && field <= HISTORY_DATA_TABLE.length) {
                return HISTORY_DATA_TABLE[field - 1];
            }
        } else if (dataTableType.equals(Constant.DataTable.HISTORY_ALARM)) {
            if (field >= 1 && field <= HISTORY_ALARM_TABLE.length) {
                return HISTORY_ALARM_TABLE[field - 1];
            }
        } else {
            throw new BusinessException(ResponseResult.TABLE_DATA_TABLE_OR_FIELD_ERROR);
        }
        return res;
    }
}
